using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;

namespace InnerFireEditor {
  public class PythonExecutor {
    private string _pythonPath;
    private string _scriptPath;
    private readonly Dictionary<string, string> _args = new Dictionary<string, string>();
    private string PYTHON_DIR = "C:\\Project\\InnerFireEditor\\Python";
    public bool Success { get; private set; }

    public PythonExecutor(string scriptPath, string pythonPath = null) {
      _scriptPath = Path.Combine(PYTHON_DIR, scriptPath);

      if (!File.Exists(_scriptPath))
        throw new FileNotFoundException("Python脚本文件不存在", scriptPath);

      _pythonPath = pythonPath ?? FindPythonPath();
    }

    /// <summary>
    /// 添加键值对参数（自动转换为小写并添加"-"前缀）
    /// </summary>
    public void SetArg(string key, object value) {
      if (string.IsNullOrWhiteSpace(key))
        throw new ArgumentException("参数名不能为空");

      string normalizedKey = key.Trim().ToLower();
      if (!normalizedKey.StartsWith("-"))
        normalizedKey = "-" + normalizedKey;

      _args[normalizedKey] = value?.ToString() ?? "";
    }

    /// <summary>
    /// 获取格式化后的参数字符串
    /// </summary>
    public string GetArgs() {
      var argList = new List<string>();
      foreach (var pair in _args) {
        // 处理值中的空格（用引号包裹）
        string escapedValue = pair.Value.Contains(" ")
            ? $"\"{pair.Value}\""
            : pair.Value;

        argList.Add($"{pair.Key} {escapedValue}");
      }
      return string.Join(" ", argList);
    }

    /// <summary>
    /// 清空所有已设置参数
    /// </summary>
    public void ClearArgs() {
      _args.Clear();
    }

    /// <summary>
    /// 执行Python脚本（直接显示控制台输出）
    /// </summary>
    public void Run() {
      string workingDir = PYTHON_DIR;
      string fullArgs = $"\"{_scriptPath}\" {GetArgs()}";

      var processInfo = new ProcessStartInfo {
        FileName = "python",
        Arguments = fullArgs,
        WorkingDirectory = workingDir,
        UseShellExecute = false,  // 必须为false才能显示控制台窗口
        CreateNoWindow = false,  // 显示控制台窗口
        RedirectStandardOutput = false,  // 不重定向输出
        RedirectStandardError = false    // 不重定向错误
      };

      string full_execute = $"python {fullArgs}";
      System.Diagnostics.Debug.WriteLine(full_execute);

      using (var process = new Process { StartInfo = processInfo }) {
        process.Start();
        process.WaitForExit();

        Success = process.ExitCode == 0;
      }
    }

    /// <summary>
    /// 自动查找系统Python路径
    /// </summary>
    private string FindPythonPath() {
      // 尝试常见Python安装路径
      string[] possiblePaths =
        {
          @"C:\Users\Administrator\AppData\Local\Programs\Python\Python310\python.exe",
          "python.exe",                   // PATH环境变量
          "python3.exe",
      };

      foreach (var path in possiblePaths) {
        try {
          var fullPath = Which(path) ?? path;
          if (File.Exists(fullPath))
            return fullPath;
        } catch { /* 忽略错误继续尝试 */ }
      }

      throw new FileNotFoundException("未找到系统Python解释器，请手动指定路径");
    }

    /// <summary>
    /// 类似Unix的which命令查找可执行文件
    /// </summary>
    private string Which(string command) {
      var paths = Environment.GetEnvironmentVariable("PATH")?.Split(';');
      if (paths == null) return null;

      foreach (var path in paths) {
        try {
          var fullPath = Path.Combine(path, command);
          if (File.Exists(fullPath))
            return fullPath;
        } catch { /* 忽略无效路径 */ }
      }

      return null;
    }

    public static string GetProcessedName(string filepath, bool use_xml_ext = false) {
      // 1. 参数校验
      if (string.IsNullOrWhiteSpace(filepath))
        return filepath;

      // 2. 标准化路径处理
      filepath = filepath.Trim();

      // 3. 检查是否已包含"_processed"
      const string suffix = "_processed";
      string filename = Path.GetFileNameWithoutExtension(filepath);
      if (filename.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) {
        return filepath; // 已有后缀则直接返回
      }

      // 4. 构建新文件名
      string dir = Path.GetDirectoryName(filepath);
      string ext = use_xml_ext ? ".xml" : Path.GetExtension(filepath);
      string newFilename = $"{filename}{suffix}{ext}";

      return Path.Combine(dir ?? string.Empty, newFilename);
    }
  }
}